<?php

namespace App\Http\Controllers\Admin;

use App\Repositories\ModuleRepository;
use App\Utils\Output;
use App\Utils\ViewHelper;
use Illuminate\Http\Request;
use App\Http\Requests\ModuleSaveRequest;

/**
 * 控制器
 * Class ModuleController
 * @package App\Http\Controllers\Admin
 */
class ModuleController extends BaseController
{
    private $rep;

    public function __construct(ModuleRepository $rep)
    {
        $this->set('module');
        $this->rep = $rep;
    }

    function index(Request $request)
    {
        $lis = $this->rep->AdminLis()->data;
        $keyword = $request->get('keyword', '');
        if (!empty($keyword)) {
            $lis = array_filter($lis, function ($item) use ($keyword) {
                return strpos($item['name'], $keyword) > -1;
            });
        }
        return $this->view('index')->with('page',$lis);
    }

    function create()
    {
        $top = $this->rep->lis(0);
        $tags = $this->rep->getNotAddControllers();
        return $this->view('create', compact('top', 'tags'));
    }

    function save(ModuleSaveRequest $request)
    {
        $data = $request->all();
        $id = $request->get('id', 0);
        return $this->rep->save($data, $id);
    }

    function edit($id)
    {
        $result = $this->rep->editInfo($id);
        if ($result->isSuccess()) {
            return $this->view('edit')->with('entity', $result->data);
        }
        return ViewHelper::E404($result->msg);
    }

    function destroy($id)
    {
        return $this->rep->destroy($id);
    }

    function actions(Request $request)
    {
        return $this->rep->getNotAddAction($request->get('name'));
    }
}
